/*
This file generates the baseline loan-level lending regressions in the 
corporate and household credit market:

	- Table 3 - Corporate credit
	- Table 4 - Household credit
	- Table 5 - Extensive margin effects in lending (corporate & household credit)
	- Table E.2 - Nonbank heterogeneity in corporate lending effects
	- Table E.3 - Nonbank heterogeneity in consumer lending effects  
*/



		
/////////////////////////////////////////////////////////////////////////////////
///
/// 					Corporate credit market 
///
/////////////////////////////////////////////////////////////////////////////////

		
/////////////////////////////////////////////////////////////////////////////////
/// Table 3 - Baseline lending regression for corporate credit
/////////////////////////////////////////////////////////////////////////////////

* Load corporate lending dataset
use if delinquency != 1 using  "${procdata}/URTEVIRK_FIRE_FIRM_03-18.dta", clear

eststo clear
* Run regressions for log debt and lending rates as outcome variables 
foreach outcome in lndebt intrate {
	
	eststo L_`outcome'_Y: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_lender year) vce(cluster id_lender#id_borrower)
	
	 eststo BL_`outcome': qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#id_lender ) vce(cluster id_lender#id_borrower)	

	eststo BL_`outcome'_Y: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#id_lender year ) vce(cluster id_lender#id_borrower)	
		
	eststo L_`outcome'_BY: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)

	eststo L_`outcome'_ILST: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(ILST_FE id_lender) vce(cluster id_lender#id_borrower)
	
	} 
	
qui estadd local MacroControlsInt "Yes": *Y *debt* *rate*
qui estadd local BorrowerYearFE "Yes": *BY*
qui estadd local LenderBorrowerFE "Yes": BL*
qui estadd local LenderFE "Yes": L_*
qui estadd local ILSTFE "Yes": *_ILST
qui estadd local YearFE "Yes": *_Y

local stats_TestFE  N r2 MacroControlsInt YearFE LenderFE LenderBorrowerFE  BorrowerYearFE ILSTFE 
local label_TestFE `""Observations" "R2" "Macro Var. Interactions"  "Year FE" "Lender FE"  "Lender-Borrower FE" "Borrower-Year FE"  "ILST FE"   "'

esttab *debt* using "${tables}/FIRMS_Regression_RobustFE.tex", ///
		prehead("{\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{6}{c}} \toprule") star(* 0.10 ** 0.05 *** 0.01) ///
		posthead("\hline \\ \multicolumn{6}{l}{\textbf{A. Outcome var: Log debt}} \\\\[-1ex]") ///
		fragment ///
		keep(inter1*) transform((exp(@)-1)*100 100*exp(@)) ///
		collabels(none)  varwidth(25)  nomtitles ///
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels(inter1 "Nonbank x MP Shock" )   ///
		stats(N r2, labels("Observations" "R2") fmt(%12.0gc 2)) replace

esttab *rate* using "${tables}/FIRMS_Regression_RobustFE.tex", ///
		posthead("\\ \multicolumn{6}{l}{\textbf{B. Outcome var: Interest rate}} \\\\[-1ex]") star(* 0.10 ** 0.05 *** 0.01) ///
		fragment append nomtitles nonumbers nolines ///
		keep(inter1*)  ///
		collabels(none)  varwidth(25)  ///
		cells(b(star fmt(3)) se(fmt(3) par)) 		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabular} }") varlabels(inter1 "Nonbank x MP Shock" )  ///
		stats(`stats_TestFE', labels(`label_TestFE') fmt(%9.0fc 2)) 


eststo clear
		
		
		
/////////////////////////////////////////////////////////////////////////////////
/// Table 5.a - Extensive margin lending effects
/////////////////////////////////////////////////////////////////////////////////

** Execute in separate frame as we re-create inter* dummies 
frame copy default ext_margin, replace
 		
frame ext_margin {
	
	// Create measure of new lending relationships
	tsspell id_borrowerlender
	gen byte new_relation = 1 if year != 2003 & _seq == 1		
	replace new_relation = 0 if year != 2003 & _seq > 1	

	qui su year
	gen byte end_relation = 1 if year != `r(max)' & _end == 1
	replace end_relation = 0 if year != `r(max)' & _end == 0

	* Need to assign lagged value of macroeconomic controls & MP shocks to new
	* lender-borrower pairs 
	preserve 
		local macrovars JK_mpshocksign DK_real_gdp_grate DK_gdp_growth_forecast ///
			DK_inflation_rate vix
		gcollapse (lastnm) `macrovars', by(year) 
		tsset year 
		foreach var of local macrovars { 
			gen L_`var' = L.`var'
		}
		keep year L_*
		tempfile lag_vars
		save `lag_vars'
	restore 

	merge m:1 year using `lag_vars', nogen keep(match master)

	*interaction terms
	cap drop inter*
	gen inter1=nonbank_lender*L_JK_mpshocksign
	gen inter2=nonbank_lender*L_DK_real_gdp_grate
	gen inter3=nonbank_lender*L_DK_gdp_growth_forecast
	gen inter4=nonbank_lender*L_DK_inflation_rate
	gen inter5=nonbank_lender*L_vix
			
	** Compute unconditional termination rates
	qui reghdfe end_relation inter1 inter2-inter5, ///
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
	gen byte insample_KM = e(sample)

	table nonbank_lender if insample_KM == 1, statistic(mean end_relation) statistic(count end_relation)


	* Regress new relationship indicator on nonbank indicator interacted with MP shock & macro controls 

	eststo L_new_relation_BY: qui reghdfe new_relation inter1 inter2-inter5, ///
		noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
		
	eststo L_new_relation_ILST: qui reghdfe new_relation inter1 inter2-inter5, ///
		noconstant a(ILST_FE id_lender) vce(cluster id_lender#id_borrower)

	* Write results to .tex file and finalize the table later with household results 
	esttab *new* using "${tables}/Regression_NewRelation.tex", ///
			prehead("{\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{3}{c}} \toprule") ///
			posthead("\hline \\ \multicolumn{3}{l}{\textbf{A. Firms}} \\\\[-1ex]") ///
			fragment star(* 0.10 ** 0.05 *** 0.01) ///
			keep(inter1*)  ///
			collabels(none)  varwidth(25)  nomtitles ///
			cells(b(star fmt(3)) se(fmt(3) par)) varlabels(inter1 "Nonbank x MP Shock" )   ///
			stats(N r2, labels("Observations" "R2") fmt(%12.0gc 2)) replace
			
} // frame ext_margin 



/////////////////////////////////////////////////////////////////////////////////
/// Table E.2 - Nonbank heterogeneity in corporate lending effects 
/////////////////////////////////////////////////////////////////////////////////

/* Replicate baseline lending analysis but instead of pooling all nonbank lenders, 
we compare each of the three largest nonbank lender types in corporate credit 
markets (Figure E.1) to traditional banks. Finally, we pool all remaining 
nonbank lenders (non top-3) and compare them to banks. 
*/

//////////////////////

eststo clear 

* Loop over each of the top-3 nonbank types 
foreach ind in 649220 649900 649100 {  
	
	preserve 
	
	cap drop nonbank_lender*	
	
	gen byte nonbank_lender = 0 if JUR_HOVED_BRA_DB07_lender == 641900	// banks
	replace nonbank_lender = 1 	if JUR_HOVED_BRA_DB07_lender == `ind'	// nonbank type
	
	drop if mi(nonbank_lender)
	
	local macrovars JK_mpshocksign DK_real_gdp_grate DK_gdp_growth_forecast ///
			DK_inflation_rate vix
			
	foreach outcome in lndebt intrate {
		eststo `outcome'_`ind': qui reghdfe `outcome' ///
			i.nonbank_lender##cL.(`macrovars'), /// 
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
	}
	
	restore 
} 

* Now pool all nonbanks that are not among the top-3 types
preserve	

cap drop nonbank_lender*
gen byte nonbank_lender = 0 if JUR_HOVED_BRA_DB07_lender == 641900 // banks

replace nonbank_lender = 1 	if inrange(GF_NACE_DB07_lender, 6420, 6700) & ///
	!inlist(JUR_HOVED_BRA_DB07_lender,649220, 649900, 649100) // non-top-3 nonbanks

drop if mi(nonbank_lender)

local macrovars JK_mpshocksign DK_real_gdp_grate DK_gdp_growth_forecast ///
			DK_inflation_rate vix

foreach outcome in lndebt intrate {
	
	eststo `outcome'_nontop3: qui reghdfe `outcome' ///
			i.nonbank_lender##cL.(`macrovars'), /// 
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
			
}
restore 
	
* Save results
qui estadd local MacroControlsInt "Yes": *
qui estadd local BorrowerYearFE "Yes": *
qui estadd local LenderFE "Yes": *

local stats_TestFE  N r2 MacroControlsInt LenderFE  BorrowerYearFE  
local label_TestFE `""Observations" "R2" "Macro Var. Interactions" "Lender FE" "Borrower-Year FE"  "'

esttab *debt_649220 *debt_649900 *debt_649100 *debt_nontop3* using ///  
		"${tables}/FIRMS_Regressions_Lending_NonbankHeterogeneity.tex", ///
		prehead("{\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{6}{c}} \toprule") ///
		posthead("\hline \\ \multicolumn{6}{l}{\textbf{A. Outcome var: Log debt}} \\\\[-1ex]") ///
		fragment star(* 0.10 ** 0.05 *** 0.01) ///
		keep(1.nonbank_lender#cL.JK_mpshocksign) transform((exp(@)-1)*100 100*exp(@)) ///
		collabels(none)  varwidth(25)   ///
		cells(b(star fmt(2)) se(fmt(2) par)) ///
		varlabels(1.nonbank_lender#cL.JK_mpshocksign "Nonbank x MP shock")   ///
		mtitles("Fin Comp"  "Wealth mngrs" "Leasing" "Non top three" )  /// 
		stats(N r2, labels("Observations" "R2") fmt(%12.0gc 2)) replace

esttab *rate_649220 *rate_649900 *rate_649100 *rate_nontop3* using /// 
		"${tables}/FIRMS_Regressions_Lending_NonbankHeterogeneity.tex", ///
		posthead("\\ \multicolumn{6}{l}{\textbf{B. Outcome var: Interest rate}} \\\\[-1ex]") ///
		fragment append nomtitles nonumbers nolines ///
		keep(1.nonbank_lender#cL.JK_mpshocksign) star(* 0.10 ** 0.05 *** 0.01) ///
		collabels(none)  varwidth(25)  ///
		cells(b(star fmt(3)) se(fmt(3) par)) 		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabular} }") ///
		varlabels(1.nonbank_lender#cL.JK_mpshocksign "Nonbank x MP shock")  ///
		stats(`stats_TestFE', labels(`label_TestFE') fmt(%9.0fc 2)) 

		
		

		
		
/////////////////////////////////////////////////////////////////////////////////
///
/// 					Consumer credit market 
///
/////////////////////////////////////////////////////////////////////////////////
		
		
/////////////////////////////////////////////////////////////////////////////////
/// Table 4 - Baseline lending regression for household credit
/////////////////////////////////////////////////////////////////////////////////

* Load household lending dataset
use if delinquency != 1 using "${procdata}/urtepers_panel_ALL.dta", clear

eststo clear 
* Run regressions for log debt and lending rates as outcome variables
foreach outcome in lndebt intrate {
	
	eststo L_`outcome'_Y: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_lender year) vce(cluster id_lender#id_borrower)
		
	eststo BL_`outcome': qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#id_lender ) vce(cluster id_lender#id_borrower)	

	eststo BL_`outcome'_Y: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#id_lender year ) vce(cluster id_lender#id_borrower)	
		
	eststo L_`outcome'_BY: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
		
	eststo L_`outcome'_ILST: qui reghdfe `outcome' inter1 inter2-inter5, ///
		noconstant a(muni_inc_lev_year_fe id_lender) vce(cluster id_lender#id_borrower)
		
} 
	
qui estadd local MacroControlsInt "Yes": *Y *debt *rate
qui estadd local BorrowerYearFE "Yes": *BY*
qui estadd local LenderBorrowerFE "Yes": BL*
qui estadd local LenderFE "Yes": L_*
qui estadd local ILSTFE "Yes": *_ILST
qui estadd local YearFE "Yes": *_Y


local stats_TestFE N r2 MacroControlsInt YearFE LenderFE LenderBorrowerFE  BorrowerYearFE ILSTFE  
local label_TestFE `" "Observations" "R2" "Macro Var. Interactions"  "Year FE" "Lender FE"  "Lender-Borrower FE" "Borrower-Year FE"  "ILST FE"  "'
	

esttab *debt* using "${tables}/URTEPERS_Regression_RobustFE.tex", ///
		prehead("{\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{6}{c}} \toprule") ///
		posthead("\hline \\ \multicolumn{6}{l}{\textbf{A. Outcome var: Log debt}} \\\\[-1ex]") ///
		fragment star(* 0.10 ** 0.05 *** 0.01) ///
		keep(inter1*) transform((exp(@)-1)*100 100*exp(@)) ///
		collabels(none)  varwidth(25)  nomtitles ///
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels(inter1 "Nonbank x MP Shock" )   ///
		stats(N r2, labels("Observations" "R2") fmt(%12.0gc 2)) replace

esttab *rate* using "${tables}/URTEPERS_Regression_RobustFE.tex", ///
		posthead("\\ \multicolumn{6}{l}{\textbf{B. Outcome var: Interest rate}} \\\\[-1ex]") ///
		fragment append nomtitles nonumbers nolines ///
		keep(inter1*) star(* 0.10 ** 0.05 *** 0.01) ///
		collabels(none)  varwidth(25)  ///
		cells(b(star fmt(3)) se(fmt(3) par)) 		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabular} }") varlabels(inter1 "Nonbank x MP Shock" )  ///
		stats(`stats_TestFE', labels(`label_TestFE') fmt(%12.0fc 2))

		
/////////////////////////////////////////////////////////////////////////////////
/// Table 5.b - Extensive margin lending effects
/////////////////////////////////////////////////////////////////////////////////

eststo clear 

** Execute in separate frame as we re-create inter* dummies 
frame copy default ext_margin, replace
 		
frame ext_margin {
				
	// Create measure of new lending relationships
	tsspell id_borrowerlender
	gen byte new_relation = 1 if year != 2003 & _seq == 1		
	replace new_relation = 0 if year != 2003 & _seq > 1	

	qui su year
	gen byte end_relation = 1 if year != `r(max)' & _end == 1
	replace end_relation = 0 if year != `r(max)' & _end == 0

	* Need to assign lagged value of macroeconomic controls & MP shocks to new
	* lender-borrower pairs 

	preserve 
		local macrovars JK_mpshocksign DK_real_gdp_grate DK_gdp_growth_forecast ///
			DK_inflation_rate vix
		gcollapse (lastnm) `macrovars', by(year) 
		tsset year 
		foreach var of local macrovars { 
			gen L_`var' = L.`var'
		}
		keep year L_*
		tempfile lag_vars
		save `lag_vars'
	restore 

	merge m:1 year using `lag_vars', nogen keep(match master)

	*interaction terms
	// MP shock measures
	cap drop inter*
	gen inter1=nonbank_lender*L_JK_mpshocksign
	gen inter2=nonbank_lender*L_DK_real_gdp_grate
	gen inter3=nonbank_lender*L_DK_gdp_growth_forecast
	gen inter4=nonbank_lender*L_DK_inflation_rate
	gen inter5=nonbank_lender*L_vix
			
	** Compute unconditional termination rates
	eststo clear 
	qui reghdfe end_relation inter1 inter2-inter5, ///
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
	gen byte insample_KM = e(sample)

	table nonbank_lender if insample_KM == 1, statistic(mean end_relation) statistic(count end_relation)


	* Regress new relationship indicator on nonbank indicator interacted with MP shock & macro controls 

	eststo L_new_relation_BY: qui reghdfe new_relation inter1 inter2-inter5, ///
		noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
		
	eststo L_new_relation_ILST: qui reghdfe new_relation inter1 inter2-inter5, ///
		noconstant a(muni_inc_lev_year_fe id_lender) vce(cluster id_lender#id_borrower)

	* Add as panel b to .tex file first generated above
	qui estadd local MacroControlsInt "Yes": *
	qui estadd local BorrowerYearFE "Yes": *BY*
	qui estadd local LenderFE "Yes": L_*
	qui estadd local ILSTFE "Yes": *_ILST

	local stats_TestFE  N r2 MacroControlsInt  LenderFE  BorrowerYearFE ILSTFE 
	local label_TestFE `""Observations" "R2" "Macro Var. Interactions"  "Lender FE"  "Borrower-Year FE"  "ILST FE"   "'


	esttab *new* using "$tables/Regression_NewRelation.tex", ///
			posthead("\\ \multicolumn{3}{l}{\textbf{B. Households}} \\\\[-1ex]") star(* 0.10 ** 0.05 *** 0.01) ///
			fragment append nomtitles nonumbers nolines ///
			keep(inter1*)  ///
			collabels(none)  varwidth(25)  ///
			cells(b(star fmt(3)) se(fmt(3) par)) 		prefoot("\hline") ///
			postfoot("\hline\hline \end{tabular} }") varlabels(inter1 "Nonbank x MP Shock" )  ///
			stats(`stats_TestFE', labels(`label_TestFE') fmt(%9.0fc 2)) 		
			
} // frame 



/////////////////////////////////////////////////////////////////////////////////
/// Table E.3 - Nonbank heterogeneity in consumer lending effects 
/////////////////////////////////////////////////////////////////////////////////
		
/* 
Replicate baseline lending analysis but instead of pooling all nonbank lenders, 
we compare each of the three largest nonbank lender types in consumer credit 
markets (Figure E.1) to traditional banks. Finally, we pool all remaining 
nonbank lenders (non top-3) and compare them to banks. 
*/


local macrovars JK_mpshocksign DK_real_gdp_grate DK_gdp_growth_forecast ///
			DK_inflation_rate vix
			
eststo clear 

* Loop over each of the top-3 nonbank types
foreach ind in  649230 649900 649100  {  
	preserve 
	
	cap drop nonbank_lender*
	
	gen byte nonbank_lender=0 if JUR_HOVED_BRA_DB07 == 641900 // banks	
	replace nonbank_lender = 1 if JUR_HOVED_BRA_DB07 == `ind' // nonbank type
	
	drop if mi(nonbank_lender)
	
	foreach outcome in lndebt intrate {
		
		eststo `outcome'_`ind': qui reghdfe `outcome' ///
			i.nonbank_lender##cL.(`macrovars'), /// 
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
	}
	
	restore 
} 

	
* Now pool all nonbanks that are not among the top-3 types
preserve 
cap drop nonbank_lender*

gen byte nonbank_lender=0 if JUR_HOVED_BRA_DB07 == 641900 // banks
replace nonbank_lender = 1 if inrange(GF_NACE_DB07_lender, 6420, 6700) & ///
	!inlist(JUR_HOVED_BRA_DB07,649220, 649900, 649100) // non-top-3 nonbank 
	
drop if mi(nonbank_lender)

foreach outcome in lndebt intrate {
	
	eststo `outcome'_nontop3: qui reghdfe `outcome' ///
			i.nonbank_lender##cL.(`macrovars'), /// 
			noconstant a(id_borrower#year id_lender) vce(cluster id_lender#id_borrower)
}
restore 
	
qui estadd local MacroControlsInt "Yes": *
qui estadd local BorrowerYearFE "Yes": *
qui estadd local LenderFE "Yes": *


local stats_TestFE  N r2 MacroControlsInt LenderFE  BorrowerYearFE 
local label_TestFE `""Observations" "R2" "Macro Var. Interactions" "Lender FE" "Borrower-Year FE" "'

esttab *debt_649230 *debt_649900 *debt_649100 *debt_nontop3* using /// 
		"$tables/URTEPERS_Regressions_Lending_NonbankHeterogeneity.tex", ///
		prehead("{\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{6}{c}} \toprule") ///
		posthead("\hline \\ \multicolumn{6}{l}{\textbf{A. Outcome var: Log debt}} \\\\[-1ex]") ///
		fragment star(* 0.10 ** 0.05 *** 0.01) ///
		keep(1.nonbank_lender#cL.JK_mpshocksign) transform((exp(@)-1)*100 100*exp(@)) ///
		collabels(none)  varwidth(25)   ///
		cells(b(star fmt(2)) se(fmt(2) par)) ///
		varlabels(1.nonbank_lender#cL.JK_mpshocksign "Nonbank x MP Shock" )   ///
		mtitles("Cons Credit" "Wealth mngr" "Leasing" "Non top three")  ///  
		stats(N r2, labels("Observations" "R2") fmt(%12.0gc 2)) replace

esttab *rate_649230 *rate_649900 *rate_649100 *rate_nontop3*  using /// 
		"$tables/URTEPERS_Regressions_Lending_NonbankHeterogeneity.tex", ///
		posthead("\\ \multicolumn{6}{l}{\textbf{B. Outcome var: Interest rate}} \\\\[-1ex]") ///
		fragment append nomtitles nonumbers nolines ///
		keep(1.nonbank_lender#cL.JK_mpshocksign) star(* 0.10 ** 0.05 *** 0.01) ///
		collabels(none)  varwidth(25)  ///
		cells(b(star fmt(3)) se(fmt(3) par)) 		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabular} }") ///
		varlabels(1.nonbank_lender#cL.JK_mpshocksign "Nonbank x MP Shock" )  ///
		stats(`stats_TestFE', labels(`label_TestFE') fmt(%12.0gc 2)) 

			
		


